import { MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { ChatService } from './chat.service';
import { ChatHistoryService } from "src/chat-history/chat-history.service";
import { UserService } from "src/user/user.service";
import { Server, Socket } from 'socket.io';
import { Inject } from '@nestjs/common';

interface JoinRoomPayload {
  chatroomId: number;
  userId: number;
}
interface SendMessagePayload {
  sendUserId: number;
  chatroomId: number;
  message: {
    type: 'text' | 'image',
    content: string;
  }
}

@WebSocketGateway({ cors: { origin: '*' } })
export class ChatGateway {
  constructor(private readonly chatService: ChatService) { }

  @Inject(ChatHistoryService)
  private chatHistoryService: ChatHistoryService;

  @Inject(UserService)
  private userService: UserService;

  @WebSocketServer()
  private server: Server;

  @SubscribeMessage('joinRoom')
  joinRoom(client: Socket, payload: JoinRoomPayload) {
    const roomName = payload.chatroomId.toString();
    // 加入房间
    client.join(roomName);
    // 向某个房间发送消息
    this.server.to(roomName).emit('message', {
      type: 'joinRoom',
      userId: payload.userId
    })
  }

  @SubscribeMessage('sendMessage')
  async sendMessage(@MessageBody() payload: SendMessagePayload) {
    const roomName = payload.chatroomId.toString();
    // 发送消息前往聊天记录表中添加一条记录，同时将发送的消息返回（这样就不用没发一次消息就查询一下聊天记录了）
    const history = await this.chatHistoryService.add(payload.chatroomId, {
      content: payload.message.content,
      type: payload.message.type === 'image' ? 1 : 0,
      chatroomId: payload.chatroomId,
      senderId: payload.sendUserId
    });

    const sender = await this.userService.findUserDetailById(history.senderId);

    this.server.to(roomName).emit('message', {
      type: 'sendMessage',
      userId: payload.sendUserId,
      message: {
        ...history,
        sender
      },
    })
  }
}
